package com.shwread.android.qysw.activity.healthy;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.shwread.android.qysw.step.HealthyConfig;
import com.shwread.android.qysw.step.adapter.GroupGamePKAdapter;
import com.shwread.android.qysw.step.api.MyAsynctask;
import com.shwread.android.qysw.step.dto.HMMatch;
import com.shwread.android.qysw.step.dto.HMMatchsDto;
import com.shwread.android.qysw.step.model.UserHealthyModel;
import com.shwread.android.qysw.step.view.LoadMoreListView;
import com.shwread.android.qysw10000204.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import logic.constants.AppConfig;

/**
 * Created by Fantasy on 16/4/3.
 */
public class GroupPKHistoryActivity extends Activity {
    @InjectView(R.id.back_btn)
    ImageView backBtn;
    @InjectView(R.id.back_text)
    TextView backText;
    @InjectView(R.id.title_text)
    TextView titleText;
    @InjectView(R.id.right_text)
    TextView rightText;
    @InjectView(R.id.right_img)
    ImageView rightImg;
    @InjectView(R.id.group_my_history_listview)
    LoadMoreListView groupMyHistoryListview;

    GroupGamePKAdapter groupGamePKAdapter;
    @InjectView(R.id.refresh_layout)
    SwipeRefreshLayout refreshLayout;
    @InjectView(R.id.no_game_text)
    TextView noGameText;
    @InjectView(R.id.no_group_game_layout)
    RelativeLayout noGroupGameLayout;
    private LinearLayoutManager linearLayoutManager;
    private int isNeedStep = 0;//0不需要,1需要


    private boolean isHasMore = true;
    private int mPage = 1;
    private List<Object> mAllList;
    private boolean isLoading = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = getIntent();
        isNeedStep = intent.getIntExtra("isNeedStep", 0);
        setContentView(R.layout.h_history_goup_game);
        ButterKnife.inject(this);
        if (isNeedStep == 1) {
            titleText.setText("历史竞赛");
        } else {
            titleText.setText("历史团赛");
        }
        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        linearLayoutManager = new LinearLayoutManager(this);
        groupMyHistoryListview.setLayoutManager(linearLayoutManager);
        mAllList = new ArrayList<>();
        groupGamePKAdapter = new GroupGamePKAdapter(GroupPKHistoryActivity.this, isNeedStep);
        groupGamePKAdapter.init_data_list(mAllList);
        groupMyHistoryListview.setLoadMoreListViewAdapter(groupGamePKAdapter);


        groupMyHistoryListview.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                int lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
                int totalItemCount = linearLayoutManager.getItemCount();
                if (lastVisibleItem >= totalItemCount - 4 && dy >= 0 && isHasMore) {
                    refreshData(mPage);
                } else if (mAllList.size() < 4 && isHasMore) {
                    refreshData(mPage);
                }
            }
        });
        isLoading = false;
        refreshData(1);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mAllList.clear();
                refreshLayout.setRefreshing(false);
                refreshData(1);
                groupGamePKAdapter.notifyDataSetChanged();
            }
        });

    }

    public void refreshData(int page) {
        if (!isLoading) {
            isLoading = true;
            HashMap<String, String> params = new HashMap<>();
            params.put("userId", UserHealthyModel.getInstance().getMyHmUserInfo().getUserId() + "");
            params.put("enterpriseId", AppConfig.getEnterpriseId());
            params.put("page", page + "");
            params.put("pageSize", HealthyConfig.loadPageCount + "");
            if (isNeedStep == 1) {
                params.put("type", "3");
                noGameText.setText("您当前没有历史的竞赛");
            } else {
                params.put("type", "2");
                noGameText.setText("您当前没有历史的团赛");
            }
            String unstartUrl = "hzlqswserver/health/game/history";
            HashMap<String, String> hashMapUrl2 = new HashMap<>();
            hashMapUrl2.put("url", unstartUrl);
            MyAsynctask asynctask = new MyAsynctask(this, new MyAsynctask.RequestListener() {
                @Override
                public void requestSuccess(String result) {
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(result);
                        String res = jsonObject.optString("returnObject");
                        if (TextUtils.isEmpty(res)) {
                            noGroupGameLayout.setVisibility(View.VISIBLE);
                        } else {
                            noGroupGameLayout.setVisibility(View.INVISIBLE);
                            Log.i("darren2", res);
                            HMMatchsDto hmMatchsDto = HMMatchsDto.parserJson(res);
                            List<HMMatch> hmMatches = hmMatchsDto.getHMMatchs();
                            if (hmMatches == null || hmMatches.size() == 0 && mPage == 1) {
                                noGroupGameLayout.setVisibility(View.VISIBLE);
                            }
                            mAllList.addAll(hmMatches);
                            groupGamePKAdapter.setTotal_data_list(mAllList);
                            groupGamePKAdapter.notifyDataSetChanged();
                            Log.i("darren", "size:----->" + hmMatchsDto.getHMMatchs().size());
                            if (hmMatchsDto.getHMMatchs().size() == HealthyConfig.loadPageCount) {
                                isHasMore = true;
                                mPage += 1;
                            } else {
                                isHasMore = false;
                            }
                            groupGamePKAdapter.setIsHasMore(isHasMore);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    isLoading = false;
                }
            });
            asynctask.execute(hashMapUrl2, params);
        }
    }
}
